<?php
/* SVN FILE: $Id: item_passavatar.php 247 2009-10-22 15:31:39Z supersmashbrothers $ */
/**
* ibMarket 2
* IP.Board 3.0
* Pass an Avatar item
*
* @author $Author: supersmashbrothers $
* @copyright $Copyright$
* @version $Revision: 247 $
* @lastrevision $Date: 2009-10-22 15:31:39 +0000 (Thu, 22 Oct 2009) $
* @modifiedby $LastChangedBy: supersmashbrothers $
* @lastmodified $LastChangedDate: 2009-10-22 15:31:39 +0000 (Thu, 22 Oct 2009) $
* @filesource $URL: http://ipb-ibmarket.googlecode.com/svn/ibmarket2/trunk/admin/applications_addon/other/ibmarket/items/other/item_passavatar.php $
*/

class item_passavatar extends templateItem
{
	/**
	 * The default name of the item
	 *
	 * @access	protected
	 * @var		string
	 */
	protected $defaultName = "Pass an Avatar";
	
	/**
	 * The default description of the item
	 *
	 * @access	protected
	 * @var		string
	 */
	protected $defaultDescription = "This item will allow you to give another person an avatar. {status}";
	
	// Inherited Properties
	/**
	 * Item setting to allow multiple instances within ibMarket 
	 *
	 * @access	protected
	 * @var		boolean
	 */
	protected $allowMultiple = true;
	
	/**
	 * Item specific setting
	 *
	 * @access	protected
	 * @var		array
	 */
	protected $itemSettings = array();
	
	/**
	 * Constructor to setup the item
	 *
	 * @access	public
	 * @param	ipsRegistry	$registry	IPB registry
	 * @param	array		&$item		The item information
	 */
	public function __construct(ipsRegistry $registry, array &$item)
	{
		parent::__construct($registry, $item);
		
		if($item['item_config'] || $item['item_id'] != 0)
		{
			$this->itemSettings = unserialize($item['item_config']);
		}
		else
		{
			$this->itemSettings['unused'] = "No Avatar Stored, use item once to store an avatar.";
			$this->itemSettings['used'] = "An Avatar Stored, use item to make the avatar yours.";
			$this->itemSettings['upload'] = 1;
		}
	}
	
	/**
	 * Additional settings when adding/editing the item
	 *
	 * @access	public
	 * @return	string|bool	string if there is something to edit, false otherwise
	 */
	public function adminForm()
	{
		$form['upload'] = ipsRegistry::getClass('output')->formYesNo('item[upload]', $this->itemSettings['upload']);
		$form['unused'] = ipsRegistry::getClass('output')->formInput('item[unused]', $this->itemSettings['unused']);
		$form['used'] = ipsRegistry::getClass('output')->formInput('item[used]', $this->itemSettings['used']);
		return <<<EOF
				<li>
					<label>{$this->lang->words['tags_for_description']}</label>
					<div style='display: inline-block'>
						{status} = {$this->lang->words['desc_status_avatar']}
						<br />
						{$this->lang->words['status_settable_below']}
					</div>
				</li>
				<li>
					<label>{$this->lang->words['pass_avatar_unused']}</label>
					{$form['unused']}
				</li>
				<li>
					<label>{$this->lang->words['pass_avatar_used']}</label>
					{$form['used']}
				</li>
				<li>
					<label>{$this->lang->words['pass_avatar_upload']}</label>
					{$form['upload']}
				</li>

EOF;
	}
	
	/**
	 * Saving to adding/editing the item
	 *
	 * @access	public
	 * @param	array	&$item_info		The new item information to be stored in the database.
	 * @param	array	[$input]		Relavent input relating to the item
	 * @return	void
	 */
	public function adminSave(array &$item_info, array $input)
	{
		$setting = array();
		$setting['upload'] = intval($input['upload']);
		$setting['unused'] = $input['unused'];
		$setting['used'] = $input['used'];
		
		$item_info['item_config'] = serialize($setting);
	}
	
	/**
	 * When quick saving the price and stock
	 *
	 * @access	public
	 * @param	array	&$item_info		The new item information to be stored in the database.
	 * @param	string	$type			Possible values: 'stockprice', more possibly in the future
	 * @return	void
	 */
	public function adminQuickSave(array &$item_info, $type)
	{
		return;
	}
	
	/**
	 * When removing the item from ibMarket
	 *
	 * @access	public
	 * @return	void
	 */
	public function adminRemove()
	{
		return;
	}
	
	/**
	 * Viewing the file edits if any
	 *
	 * @access	public
	 * @return	string|bool	string if there is something to edit, false otherwise
	 */
	public function adminViewFileEdits()
	{
		return false;
	}
	
	/**
	 * Any admin AJAX functionality
	 *
	 * @access	public
	 * @param	array	$invItem		The inventory item
	 * @return	void
	 */
	public function adminAjax()
	{
		return;
	}
	
	/**
	 * Check and modify the intentory item information before storing in the database
	 *
	 * @access	public
	 * @param	array	&$invItem		The new inventory item information to be stored in the database.
	 * @return	bool	true if the item is successfully created, false otherwise
	 */
	public function publicOnCreateItem(array &$invItem)
	{
		return true;
	}
	
	/**
	 * When using the item
	 * Show a form and validate the form
	 *
	 * @access	public
	 * @param	array	$invItem		The inventory item
	 * @return	string|bool				string if there is a form to be used, true if successfully used, false otherwise
	 */
	public function publicUseItem(array &$invItem)
	{
		$setting = unserialize($invItem['settings']);
		$this->registry->getClass('class_localization')->loadLanguageFile( array( 'public_items' ) );
		$this->registry->getClass('class_localization')->loadLanguageFile( array( 'public_usercp' ), 'core' );
		
		if($setting['avatar'])
		{
			IPSMember::getFunction()->removeAvatar($this->memberData['member_id']);
			
			IPSMember::save( $this->memberData['member_id'], array( 'extendedProfile' => array( 'avatar_type' => 'url', 'avatar_location' => $setting['avatar'], 'avatar_size' => $setting['dimensions'] ) ) );
			
			$this->deleteItems($invItem);
			
			$this->writeLog($invItem, "Changed avatar");
			
			$this->registry->getClass('output')->redirectScreen( $this->lang->words['avatar_updated'], $this->settings['base_url_with_app'] . "module=inventory" );
		}
		if($this->request['request_method'] == 'post')
		{
			list($p_width, $p_height)	= explode( "x", strtolower( $this->settings['avatar_dims'] ) );
			
			//-----------------------------------------
			// Upload?
			//-----------------------------------------
			
			if( $_FILES['upload_avatar']['name'] != "" AND $_FILES['upload_avatar']['name'] != "none" )
			{
				$this->settings[ 'upload_dir'] =  str_replace( '&#46;', '.', $this->settings['upload_dir']  );
				
				$real_name = 'av-item-' . $invItem['i_id'];
				
				require_once( IPS_KERNEL_PATH.'classUpload.php' );
				$upload = new classUpload();
				
				$upload->out_file_name     = $real_name;
				$upload->out_file_dir      = $this->settings['upload_dir'];
				$upload->max_file_size     = ($this->settings['avup_size_max'] * 1024) * 8;  // Allow xtra for compression
				$upload->upload_form_field = 'upload_avatar';
				
				//-----------------------------------------
				// Populate allowed extensions
				//-----------------------------------------
				
				if ( is_array( $this->cache->getCache('attachtypes') ) and count( $this->cache->getCache('attachtypes') ) )
				{
					foreach( $this->cache->getCache('attachtypes') as $data )
					{
						if ( $data['atype_photo'] )
						{
							if( $data['atype_extension'] == 'swf' AND $this->settings['disable_flash'] )
							{
								continue;
							}
							
							$upload->allowed_file_ext[] = $data['atype_extension'];
						}
					}
				}
				
				//-----------------------------------------
				// Upload...
				//-----------------------------------------
				
				$upload->process();
				
				//-----------------------------------------
				// Error?
				//-----------------------------------------
				
				if ( $upload->error_no )
				{
					$this->registry->getClass('output')->showError('upload_failed');
				}
				
				$real_name	= $upload->parsed_file_name;
				$im			= array();
				
				if ( ! $this->settings['disable_ipbsize'] and $upload->file_extension != '.swf' )
				{
					$imageDimensions = getimagesize( $this->settings['upload_dir'] . '/' . $real_name );
					
					if( $imageDimensions[0] > $p_width OR $imageDimensions[1] > $p_height )
					{
						require_once( IPS_KERNEL_PATH."classImage.php" ); 
						require_once( IPS_KERNEL_PATH."classImageGd.php" );
						$image = new classImageGd();
						
						$image->init( array( 
												 'image_path'     => $this->settings['upload_dir'], 
												 'image_file'     => $real_name, 
									   )          );
						
						$return = $image->resizeImage( $p_width, $p_height );
						$image->writeImage( $this->settings['upload_dir'] . '/' . $real_name );
						
						$im['img_width']  = $return['newWidth'] ? $return['newWidth'] : $image->cur_dimensions['width'];
						$im['img_height'] = $return['newHeight'] ? $return['newHeight'] : $image->cur_dimensions['height'];
					}
					else
					{
						$im['img_width']  = $imageDimensions[0];
						$im['img_height'] = $imageDimensions[1];
					}
				}
				else
				{	
					$w 					= intval($this->request['man_width'])  ? intval($this->request['man_width'])  : $p_width;
					$h 					= intval($this->request['man_height']) ? intval($this->request['man_height']) : $p_height;
					$im['img_width']	= $w > $p_width  ? $p_width  : $w;
					$im['img_height']	= $h > $p_height ? $p_height : $h;
				}
				
				//-----------------------------------------
				// Set the "real" avatar..
				//-----------------------------------------
				
				$avatar['avatar_location']		= $this->settings['upload_url'] . '/' . $real_name;
				$avatar['avatar_size']			= $im['img_width'].'x'.$im['img_height'];
				$avatar['avatar_type']			= 'url';
			}
			
			//-----------------------------------------
			// URL?
			//-----------------------------------------
			
			else if( $this->request[ 'avatar_url' ] AND IPSText::xssCheckUrl( $this->request[ 'avatar_url' ] ) === true )
			{
				$ext 		= explode ( ",", $this->settings['avatar_ext'] );
				$checked 	= 0;
				$av_ext 	= preg_replace( "/^.*\.(\S+)$/", "\\1", $this->request['avatar_url'] );
				
				foreach( $ext as $v  )
				{
					if( strtolower( $v ) == strtolower( $av_ext ) )
					{
						if( $v == 'swf' AND $this->settings['disable_flash'] )
						{
							$this->registry->getClass('output')->showError('saveavatar_badimgext');
						}
						
						$checked = 1;
						break;
					}
				}
				
				if( $checked != 1 )
				{
					$this->registry->getClass('output')->showError('saveavatar_badimgext');
				}
				
				if ( ! $this->settings['disable_ipbsize'] )
				{
					if ( ! $img_size = @getimagesize( $this->request['avatar_url'] ) )
					{
						$img_size[0] = $p_width;
						$img_size[1] = $p_height;
					}
					
					$im = IPSLib::scaleImage( array(
													'max_width'  => $p_width,
													'max_height' => $p_height,
													'cur_width'  => $img_size[0],
													'cur_height' => $img_size[1]
											)		);
				}
				else
				{	
					$w					= intval($this->request['man_width'])  ? intval($this->request['man_width'])  : $p_width;
					$h					= intval($this->request['man_height']) ? intval($this->request['man_height']) : $p_height;
					$im['img_width']	= $w > $p_width  ? $p_width  : $w;
					$im['img_height']	= $h > $p_height ? $p_height : $h;
				}
				
				$avatar['avatar_location']		= trim( $this->request[ 'avatar_url' ] );
				$avatar['avatar_size']			= $im['img_width'].'x'.$im['img_height'];
				$avatar['avatar_type']			= 'url';
			}
			
			if(!$avatar)
			{
				$this->registry->getClass('output')->showError('saveavatar_noimg2');
			}
			
			$settings = array('avatar' => $avatar['avatar_location'], 'dimensions' => $avatar['avatar_size']);
			$this->DB->update('market_inventory',array(
														'settings' => serialize($settings),
							),'i_id='.$invItem['i_id']);
			
			$this->registry->getClass('output')->redirectScreen( $this->lang->words['avatar_stored'], $this->settings['base_url_with_app'] . "module=inventory" );
		}
		
		$max = $this->itemSettings['upload_size'] * 1024;
 		if ( $this->itemSettings['upload_size'] )
 		{
 			$this->lang->words['pph_max']  = sprintf( $this->lang->words['pph_max'], $this->itemSettings['upload_size'] );
 			$this->lang->words['pph_max'] .= sprintf( $this->lang->words['pph_max2'], $this->itemSettings['upload_width'], $this->itemSettings['upload_height'] );
 		}
 		else
 		{
 			$this->lang->words['pph_max'] = sprintf( $this->lang->words['pph_max2'], $this->itemSettings['upload_width'], $this->itemSettings['upload_height'] );
 		}
		
		$html = <<<EOF
<form id='passAvatarForm' enctype="multipart/form-data" method="post" action="{$this->settings['base_url_with_app']}module=inventory&amp;section=item&amp;item={$invItem['i_id']}">
	<div id='passAvatar'class='block_wrap'>
		<h3 id='passAvatarHeader' class='maintitle'>{$this->item['item_name']}</h3>
		<fieldset class='row1'>
			<h3>{$this->lang->words['avatar_url_title']}</h3>
			<p class='message unspecific'>
EOF;
		list( $this->settings['maxWidth'], $this->settings['maxHeight'] ) = explode( "x", strtolower($this->settings['avatar_dims'] ) );
		$html .= sprintf( $this->lang->words['av_text_url'], $this->settings['maxWidth'], $this->settings['maxHeight'] );
		if($this->itemSettings['upload'])
		{
			$html .= <<<EOF
					<br />

EOF;
			$html .= sprintf( $this->lang->words['av_text_upload'], $this->settings['avup_size_max'] );
		}
		$this->lang->words['av_allowed_files'] = sprintf($this->lang->words['av_allowed_files'], implode (' .', explode( "|", $this->settings['avatar_ext'] ) ) );
		$html .= <<<EOF
				<br />{$this->lang->words['av_allowed_files']}
			</p>
			<ul>

EOF;
		if($this->itemSettings['upload'])
		{
			$html .= <<<EOF
				<li class='field'>
					<label for='upload_avatar'>{$this->lang->words['av_upload']}</label>
					<input type="file" size="30" name="upload_avatar" id="upload_avatar" />
				</li>

EOF;
		}
		$html .= <<<EOF
				<li class='field'>
					<label for='avatar_url'>{$this->lang->words['av_url']}</label>
					<input type="text" size="40" maxlength="80" name="avatar_url" id="avatar_url" value="{$data['current_url_avatar']}" />
				</li>
			</ul>

EOF;
		if( ! $this->settings['disable_ipbsize'] )
		{
			$html .= <<<EOF
			<p><strong>{$this->lang->words['av_autosize']}</strong><br />({$this->lang->words['av_as_desc']})</p>

EOF;
		}
		else
		{
			$html .= <<<EOF
			<ul>
				<li class='field'>
					{$this->lang->words['width']}
					<input type="text" size="3" name="man_width" />
				</li>
				<li class='field'>
					{$this->lang->words['height']}
					<input type="text" size="3" name="man_height" />
				</li>
			</ul>

EOF;
		}
		$html .= <<<EOF
		</fieldset>
		<fieldset class="submit">
			<input class="input_submit" type="submit" value="{$this->lang->words['store_avavtar']}" name="submit" />
		</fieldset>
	</div>
</form>
<script type='text/javascript'>
if( $('member_name') )
{
	new ipb.Autocomplete( $('member_name'), { multibox: false, url: ipb.vars['base_url'] + 'app=core&module=ajax&section=findnames&do=get-member-names&secure_key={$this->member->form_hash}&name=', templates: { wrap: ipb.templates['autocomplete_wrap'], item: ipb.templates['autocomplete_item'] } } );
}
</script>
EOF;
		return $html;
	}
	
	/**
	 * Any AJAX functionality
	 *
	 * @access	public
	 * @param	array	$invItem		The inventory item
	 * @return	void
	 */
	public function publicAjax(array &$invItem)
	{
		return;
	}
	
	/**
	 * When the item is being sold back
	 *
	 * @access	public
	 * @param	array	&$invItem	The inventory item information
	 * @return	bool				true if successful, false otherwise
	 */
	public function publicOnResoldItem(array &$invItem)
	{
		return true;
	}
	
	/**
	 * When the item is being restocked
	 *
	 * @access	public
	 * @param	array	&$item	The inventory item information
	 * @return	void
	 */
	public function onItemRestock(array &$item)
	{
		return;
	}
	
	/**
	 * Get the description of the item, normally called when there is no intentory item being used
	 *
	 * @access	public
	 * @return	string
	 */
	public function parseStoreDescription()
	{
		return str_replace('{status}', '', $this->item['item_description']);
	}
	
	/**
	 * Get the description of the item, normally called when there is one intentory items being used
	 *
	 * @access	public
	 * @param	array	$invItem	The inventory item information
	 * @return	string
	 */
	public function parseInventoryDescription(array $invItem)
	{
		$setting = unserialize($invItem['settings']);
		return str_replace('{status}',$setting['avatar'] ? $this->itemSettings['used'] : $this->itemSettings['unused'],$this->item['item_description']);
	}
}
